/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sunrise.validator;

import com.sunrise.boundary.UserManager;
import com.sunrise.entity.User;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

/**
 *
 * @author frank
 */
@RequestScoped
@FacesValidator("emailValidator")
public class EmailValidator implements Validator {

    @EJB
    private UserManager userManager;

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {

        String emailInputText = (String) value;
        String emailRegex = "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?";

        if (emailInputText.length() == 0) {
            throwExceptionWithErrorMessage("Email cannot be empty");
        } else if (emailInputText.length() > 255) {
            throwExceptionWithErrorMessage("Email cannot be longer than 255 characters");
        }

        if (!emailInputText.matches(emailRegex)) {
            throwExceptionWithErrorMessage("Invalid email");
        }
        
        User user = userManager.findUserByEmail(emailInputText);
        

        if (user != null) {
            throwExceptionWithErrorMessage("This email is already associated to another user");
        }
    }

    private void throwExceptionWithErrorMessage(String error) {
        FacesMessage msg = new FacesMessage("", error);
        msg.setSeverity(FacesMessage.SEVERITY_ERROR);
        throw new ValidatorException(msg);
    }

}
